<template>
    <div class="zy-content">
      <back-level :go-page="close"></back-level>
        <Card
            :title="$t('spareParts.From')"
            class="detail-content-layout nopad"
            v-if="$route.query.status !== 'detail'"
        >
<!--            <div slot="extra" @click.prevent="close">-->
<!--                <Icon type="ios-close-circle-outline" size="20"/>-->
<!--            </div>-->
            <template >
                <div class="basic-info">
<!--                    <div class="basic-info-title">-->
<!--                        <h2>{{ $t('spareParts.From') }}</h2>-->
<!--                    </div>-->
                    <div class="basic-info-body">
                      <div class="searchBox search-box-layout noBg">
                        <Row :gutter="24">
                          <Col span="4">
                            <div>
                              <p class="label">{{$t('spareParts.PartNoGoodsNameSpecification')}}</p>
                              <div class="ipt">
                                <Select filterable
                                        v-model="searchParams.materielNo"
                                        :remote-method="remoteMethod"
                                        clearable
                                        @on-change="handleMaterielNo"
                                        :placeholder="`${$t('common.inputInfo')}`">
                                  <Option v-for="item of materielNoList"
                                          :value="item.id"
                                          :label="item.materielNo"
                                          :key="item.id">
                                    {{ item.materielNo + '-' + item.goodsName + '-' + item.specification + '-' + item.purchaseOrderNo }}
                                  </Option>
                                </Select>
                              </div>
                            </div>
                          </Col>
                          <Col span="4">
                            <div>
                              <p class="label">{{$t('common.SpareNumber')}}</p>
                              <div class="ipt">
                                <Select filterable
                                        v-model="searchParams.purchaseOrderNo"
                                        clearable
                                        :placeholder="`${$t('common.selectInfo')}`"
                                        :remote-method="remoteMethodOne"
                                        @on-change="handlePurchaseOrderNo">
                                  <Option v-for="item of backupNoList"
                                          :value="item.value"
                                          :label="item.label"
                                          :key="item.value"/>
                                </Select>
                              </div>
                            </div>
                          </Col>
                          <Col span="4">
                            <div>
                              <p class="label">{{$t('maintenance.EquipmentNo')}}</p>
                              <div class="ipt">
                                <Input v-model="searchParams.deviceNo" disabled/>
                              </div>
                            </div>
                          </Col>
                          <Col span="4">
                            <div>
                              <p class="label">{{$t('spareParts.company')}}</p>
                              <div class="ipt">
                                <Select v-model="searchParams.companyId"
                                        @on-change="changeCompany"
                                        clearable :placeholder="`${$t('common.selectInfo')}`">
                                  <Option v-for="item of tagList"
                                          :value="item.id"
                                          :label="item.name"
                                          :key="item.id"/>
                                </Select>
                              </div>
                            </div>
                          </Col>
                          <Col span="4">
                            <div>
                              <p class="label">{{$t('common.Returnedby')}}</p>
                              <div class="ipt">
                                <Select
                                    v-model="createBy"
                                    filterable
                                    disabled
                                    clearable
                                    :placeholder="`${$t('common.inputInfo')}`"
                                >
                                  <Option v-for="item in OAList"
                                          :value="item.id"
                                          :label="item.showName"
                                          :key="item.id"/>
                                </Select>
                              </div>
                            </div>
                          </Col>
                          <Col span="4">
                            <div>
                              <p class="label">{{$t('spareParts.Scrap')}}</p>
                              <div class="ipt">
                                <RadioGroup v-model="searchParams.scraped" @on-change="radioChange">
                                  <Radio :disabled="radioDisable" label="1">{{ $t('common.Yes') }}</Radio>
                                  <Radio label="0">{{ $t('common.No') }}</Radio>
                                </RadioGroup>
                              </div>
                            </div>
                          </Col>
                          <Col span="24">
                            <div class="t-c">
                              <div class="ipt">
                                <Button class="search-btn" type="primary" v-if="$route.query.status === 'add'" @click="addinfon">{{$t('保存添加')}}
                                </Button>
                                <Button
                                    class="reset-btn"
                                    @click="changeNum()"
                                >{{ $t('common.reset') }}
                                </Button>
                              </div>
                            </div>
                          </Col>
                        </Row>
                      </div>
                    </div>
                </div>
            </template>


        </Card>
      <Card
          :title="$t('spareParts.To')"
          class="detail-content-layout mt16 nopad"
      >
        <div class="basic-info tableContent" style="border: none">
          <!--                <div class="basic-info-title  basic-info-title_bot">-->
          <!--                    <h2>{{ $t('spareParts.To') }}</h2>-->
          <!--                </div>-->
          <div class="basic-info-body tableContent mt16">
            <Table class="resizable-table" border @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,tarGetscraped == 1 ?'scrapTableColumns':'tableColumnskeys')}" :columns="columnsInfo" :data="tablelist">
              <template #revertNum="{ row,index}">
                <Input :disabled="$route.query.status === 'detail'" v-model="tablelist[index].revertNum"/>
              </template>
              <template #action="{ row }">
                <div class="ivu-table-cell-slot">
                  <span class="operationBtn" @click="delRow(row)"><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>
                </div>
              </template>

              <template #remark="{ row,index}">
                <Input :disabled="$route.query.status === 'detail'" v-model="tablelist[index].remark"/>
              </template>
              <template slot-scope="{ row }" slot="companyName">
                <span>{{ row.companyName }}</span>
              </template>
              <template #warehouseId="{ row }">
                <Select
                    :transfer="true"
                    v-model="row.warehouseId"
                    :disabled="$route.query.status === 'detail'"
                    @on-change="warehouseChange(1,row)"
                    :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="item of row.warehouserowList"
                          :value="item.id"
                          :label="item.backupName"
                          :key="item.id"/>
                </Select>
              </template>

              <template #shelfConfigId="{ row }">
                <Select
                    :transfer="true"
                    :disabled="$route.query.status === 'detail'"
                    v-model="row.shelfConfigId"
                    @on-change="shelvesChange(1,row)"
                    :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="item of row.shelvesrowList"
                          :value="item.id"
                          :label="item.shelf"
                          :key="item.id"/>
                </Select>
              </template>

              <template #locationId="{ row }">
                <!--              <span v-if="$route.query.status === 'detail'"></span>-->
                <Select
                    :transfer="true"
                    :disabled="$route.query.status === 'detail'"
                    v-model="row.locationId"
                    @on-change="locationChange(row)"
                    :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="item of row.locationrowList"
                          :value="item.id"
                          :label="item.location"
                          :key="item.id"/>
                </Select>
              </template>

              <template slot-scope="{ row }" slot="scrapCount">
                            <span
                                v-if="$route.query.status ==='detail' || row.assetId !== 2">{{ row.scrapCount }}</span>
                <Input v-else
                       :disabled="$route.query.status ==='detail'"
                       v-model="row.scrapCount"
                       number
                       @on-keyup="levelCheck"
                       @on-change="outNumchange(row)"/>
              </template>

              <template slot-scope="{ row }" slot="assetsOriginal">
                <span v-if="$route.query.status ==='detail'">{{ row.assetsOriginal }}</span>
                <Input v-else
                       :disabled="$route.query.status ==='detail'|| row.assetId == 2"
                       @on-change="originalChange(row)"
                       v-model="row.assetsOriginal"
                />
              </template>
              <template slot-scope="{ row }" slot="assets">
                <span v-if="$route.query.status ==='detail'">{{ row.assets }}</span>
                <Input v-else
                       disabled
                       v-model="row.assets"
                />
              </template>
              <template slot-scope="{ row }" slot="useTime">
                <span v-if="$route.query.status ==='detail'">{{ row.useTime }}</span>
                <Input v-else-if="row.useTime || '0'"
                       :disabled="$route.query.status ==='detail' || row.assetId == 2"
                       v-model="row.useTime"
                />
                <Date-picker
                    v-else
                    :transfer="true"
                    type="daterange"
                    placement="bottom-end"
                    placeholder="选择日期"
                    :disabled="$route.query.status ==='detail' || row.assetId == 2"
                    @on-change="dateChang($event,row)"
                />
              </template>
              <template slot-scope="{ row }" slot="useDept">
                <span v-if="$route.query.status ==='detail'">{{ row.useDept }}</span>
                <Input v-else :disabled="$route.query.status ==='detail'"
                       @on-change="remarkNumchange(row)"
                       v-model="row.useDept"
                />
              </template>
              <template slot-scope="{ row }" slot="deptCostCenter">
                <span v-if="$route.query.status ==='detail'">{{ row.deptCostCenter }}</span>
                <Input v-else :disabled="$route.query.status ==='detail'"
                       @on-change="remarkNumchange(row)"
                       v-model="row.deptCostCenter"
                />
              </template>
              <template slot-scope="{ row }" slot="scrapReason">
                <span v-if="$route.query.status ==='detail'">{{ row.scrapReason }}</span>
                <Input v-else :disabled="$route.query.status ==='detail'"
                       v-model="row.scrapReason"
                       @on-change="remarkNumchange(row)"/>
              </template>

            </Table>
          </div>
        </div>
      </Card>
      <bottom-handle-wrap v-if="$route.query.status === 'add'">
        <Button class="mr16" @click.prevent="close">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click.prevent="onsumbit">{{ $t('maintenance.Confirmed') }}</Button>
      </bottom-handle-wrap>
    </div>
</template>

<script>
// import recursion from "@/util/recursion";
import {
    getCompanyList,
    getBackupsByCompany,
    getShelfByBackupId,
    getLocationByShelfId,
    baogetLocationByShelfId
} from "@/api/index.js";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
    name: "recipientsrevertModule",
    mixins:[toggleTableOperation],
    data() {
        return {
            tarGetscraped: "",
            pageNum: 1,
            createBy: '',
            pageSize: 10,
            radioDisable: false,
            searchParams: {
                scraped: "0"
            },
            orgList: [],
            tagList: [],
            tablelist: [],
            columnsInfo: [],
            backupNoList: [],
            materielNoList: [],
            materielNoObj: {},
            formRule: {
                materielNo: [
                    {required: true, message: `${this.$t('acceptanceCheck.selectMaterielNo')}`, trigger: 'blur', type: 'number'}
                ],
                purchaseOrderNo: [
                    {required: true, message: `${this.$t('acceptanceCheck.inputPurchaseOrderNo')}`, trigger: 'change'}
                ],
                companyId: [
                    {required: true, message: `${this.$t('acceptanceCheck.selectCompany')}`, trigger: 'change', type: 'number'}
                ],
                scraped: [
                    {required: true, message: `${this.$t('acceptanceCheck.selectScraped')}`, trigger: 'change'}
                ]
            },
            tableColumns: [
                {
                    title: `${this.$t('spareParts.PartNo')}`,
                    key: 'materielNo',
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.SpareNumber')}`,
                    key: 'purchaseOrderNo',
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.GoodsName')}`,
                    key: 'goodsName',
                    align: "center",
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.Specification')}`,
                    key: 'specification',
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.Warehouse')}`,
                    key: 'warehouseId',
                    slot: "warehouseId",
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.Rack')}`,
                    key: 'shelfConfigId',
                    slot: "shelfConfigId",
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.Location')}`,
                    key: 'locationId',
                    slot: "locationId",
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.ReturnQuantity')}`,
                    key: 'revertNum',
                    slot: "revertNum",
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.ReturnReson')}`,
                    key: 'remark',
                    slot: "remark",
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.operation')}`,
                    slot: "action",
                    fixed: 'right',
                    minWidth: 50,
                    align: "center"
                }
            ],
            scrapTableColumns: [
                {
                    title: `${this.$t('spareParts.PartNo')}`,
                    key: 'materielNo',
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.SpareNumber')}`,
                    key: 'purchaseOrderNo',
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.GoodsName')}`,
                    key: 'goodsName',
                    align: "center",
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.Specification')}`,
                    key: 'specification',
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.company')}`,
                    key: 'companyName',
                    slot: "companyName",
                    align: "center",
                resizable: true
                },
                {
                    title: `${this.$t('spareParts.Warehouse')}`,
                    key: 'warehouseId',
                    slot: "warehouseId",
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.Rack')}`,
                    key: 'shelfConfigId',
                    slot: "shelfConfigId",
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.Location')}`,
                    key: 'locationId',
                    slot: "locationId",
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.ScrapQuantity')}`,
                    key: 'scrapCount',
                    slot: "scrapCount",
                    align: "center",
                resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.OriginalValue')}`,
                    key: 'assetsOriginal',
                    slot: "assetsOriginal",
                    align: "center",
                    resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.ResidualValue')}`,
                    key: 'assets',
                    slot: "assets",
                    align: "center",
                    resizable: true
                },
                {
                    title: `${this.$t('使用年限')}`,
                    key: 'useTime',
                    slot: "useTime",
                    align: "center",
                    resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.UsedDept')}`,
                    key: 'useDept',
                    slot: "useDept",
                    align: "center",
                    resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.CostCenter')}`,
                    key: 'deptCostCenter',
                    slot: "deptCostCenter",
                    align: "center",
                    resizable: true
                },
                {
                    title: `${this.$t('spareParts.ScrapReason')}`,
                    key: 'scrapReason',
                    slot: "scrapReason",
                    align: "center",
                    resizable: true
                },
                {
                    title: `${this.$t('common.operation')}`,
                    slot: "action",
                    fixed: 'right',
                    minWidth: 40,
                    align: "center"
                }
            ],
            depreciationInfo: '',
            OAList: [],
            timeID: null,
            flagId: 0
        }
    },
    mounted() {
        this.getColumnWidth(this.tarGetscraped == 1 ?this.scrapTableColumns:this.tableColumns,this.tarGetscraped == 1 ?'scrapTableColumns':'tableColumnskeys')
        this.getCompanyList()
        this.getApplicationOAList(localStorage.getItem('ziyunFactoryPortalName'))
        if (this.$route.query.status === 'detail') {
            this.searchList()
            // this.tableColumns = this.tableColumns.splice(0,this.tableColumns.length-1)
        }
      let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))
      for (let item of itemList) {
        if (item.code == "scrappAply") {
          this.radioDisable = false
        }else {
          this.radioDisable = true
          this.searchParams.scraped = '0'
        }
      }
        this.columnsInfo = this.tableColumns
    },
    methods: {
        radioChange(val) {
            this.columnsInfo = []
            if (val == 1) {
                this.columnsInfo = this.scrapTableColumns
            } else {
                this.columnsInfo = this.tableColumns
            }
            this.tarGetscraped = val
        },
        levelCheck(e) {
            e.target.value = e.target.value.replace(/(^\s*)|(\s*$)/g, "");
            const reg = /[^\d.]/g;
            e.target.value = e.target.value.replace(reg, "");
            e.target.value = e.target.value.replace(/^\./g, "");
            e.target.value = e.target.value
                .replace(".", "$#$")
                .replace(/\./g, "")
                .replace("$#$", ".");
            e.target.value = e.target.value.replace(
                /^(\-)*(\d+)\.(\d\d).*$/,
                "$1$2.$3"
            );
        },
        outNumchange(row) {
            if (this.timeID) {
                clearTimeout(this.timeID)
            }
            this.timeID = setTimeout(() => {
                this.tablelist.forEach(val => {
                    if (val.id === row.id) {
                        val.scrapCount = Number(row.scrapCount)
                        if (Number(val.quantityInStock) < Number(row.scrapCount)) {
                            this.$Message.warning(({
                                content: '当前报废数量不得大于库存数量!',
                                duration: 6,
                                closable: true
                            }));
                            val.scrapCount = ''
                        }
                    }
                })
            }, 600);
        },
        //计算资产残值
        getassetsData(row) {
            if (this.timerId) {
                clearTimeout(this.timerId)
            }
            const params = {
                days: row.useTime,
                original: row.assetsOriginal,
                depreciation: this.depreciationInfo
            }
            this.timerId = setTimeout(() => {
                this.axios({
                    method: 'get',
                    url: '/dms/backup/scrapApply/calculationAsset',
                    params
                }).then(res => {
                    if (res.code === 200) {
                        if (res.data) {
                            this.$set(row, 'assets', res.data)
                            this.tablelist.forEach(val => {
                                if (val.id === row.id) {
                                    val.assets = res.data
                                }
                            })
                        }
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                })
            }, 600)
        },
        getDays(start, end) {
            let dateSpan, iDays
            start = Date.parse(start)
            end = Date.parse(end)
            dateSpan = end - start
            dateSpan = Math.abs(dateSpan)
            iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
            return iDays;
        },
        originalChange(row) {
            this.tablelist.forEach(val => {
                if (val.id === row.id) {
                    val.assetsOriginal = row.assetsOriginal
                    val.useTime = row.useTime
                }
            })
            if (row.useTime && row.assetsOriginal && this.depreciationInfo) {
                this.getassetsData(row)
            }
        },
        remarkNumchange(row) {
            this.tablelist.forEach(val => {
                if (val.id === row.id) {
                    val.scrapReason = row.scrapReason
                    val.useDept = row.useDept
                    val.deptCostCenter = row.deptCostCenter
                }
            })
        },
        dateChang(val, row) {
            if (val && val.length) {
                const days = this.getDays(val[0], val[1])
                this.$set(row, 'useTime', days)
                if (row.assetsOriginal) {
                    this.originalChange(row)
                }
            }
        },
        getApplicationOAList(query) {
            if (query !== '') {
                this.loading = true
                this.axios({
                    method: 'get',
                    url: '/basic/user/searchOAUser',
                    params: {
                        key: query
                    }
                }).then(res => {
                    if (res.code === 200) {
                        this.OAList = res.data.map(item => {
                            return {
                                ...item,
                                showName: item.empno + '----' + item.username
                            }
                        })
                        this.createBy = Number(localStorage.getItem('ziyunFactoryUserId'))
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.loading = false
                })
            } else {
                this.OAList = []
            }
        },
        changeCompany(val) {
            if (val) {
                //this.searchParams.companyId = val
                this.searchParams.companyName = this.tagList.find(item => item.id == val).name
            }
        },
        onsumbit() {
            let arr = this.tablelist.map(obj => (
                {
                    id: obj.id,
                    createBy: obj.createBy,
                    purchasePrice: obj.purchasePrice,
                    standingBookId: obj.standingBookId,
                    applyUseId: obj.applyUseId,
                    companyId: obj.companyId,
                    companyName: obj.companyName,
                    materielNo: obj.materielNo,
                    purchaseOrderNo: obj.purchaseOrderNo,
                    goodsName: obj.goodsName,
                    specification: obj.specification,
                    scraped: obj.scraped/1,
                    warehouseName: obj.warehouseName,
                    warehouseId: obj.warehouseId,
                    locationId: obj.locationId,
                    location: obj.location,
                    shelfConfigId: obj.shelfConfigId,
                    shelf: obj.shelf,
                    assets: obj.assets,//资产残值
                    assetsOriginal: obj.assetsOriginal,//资产原值
                    revertNum: obj.scrapCount,//报废数量
                    manageType: obj.manageType,//管理类型
                    useTime: obj.useTime,//使用时间
                    useDept: obj.useDept,//使用部门
                    deptCostCenter: obj.deptCostCenter,//部门成本中心
                    remark: obj.scrapReason,//报废原因
                    assetId: obj.assetId,//资产分类主键id
                }
            ))
            this.axios({
                method: 'post',
                url: '/dms/revert/add',
                data: [...arr]
            }).then(res => {
                if (res.code == 200) {
                    this.close()
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        addinfon() {
          this.axios({
            method: 'get',
            url: '/dms/backup/scrapApply/checkBackupCanBeScrap',
            params: {
              scrapSource: 1,
              backupId: this.materielNoObj.backupId
            }
          }).then(res => {
            if (res.code === 200) {
              this.addTableinfo(res.data)
              this.depreciationInfo = res.data.depreciation
              this.backupNoList = [];
              // this.$refs.selectFrom.resetFields();
            } else {
              this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
            }
          })
            // this.$refs.selectFrom.validate((valid) => {
            //     if(valid){
            //         this.axios({
            //             method: 'get',
            //             url: '/dms/backup/scrapApply/checkBackupCanBeScrap',
            //             params: {
            //                 scrapSource: 1,
            //                 backupId: this.materielNoObj.backupId
            //             }
            //         }).then(res => {
            //             if (res.code === 200) {
            //                 this.addTableinfo(res.data)
            //                 this.depreciationInfo = res.data.depreciation
            //                 this.backupNoList = [];
            //                 this.$refs.selectFrom.resetFields();
            //             } else {
            //                 this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
            //             }
            //         })
            //     }
            // })
        },
        async addTableinfo(obj) {
            if (!obj.assetId) {
                obj.assetId = 2
            }
            if (obj.assetId !== 2) {
                obj.scrapCount = 1
                obj.revertNum = 1
            }
            // this.flagId++;
            let tableObj;
            if (this.searchParams.scraped == 1) {
                tableObj = {
                    id: obj.id,
                    assetId: obj.assetId,//资产分类主键id
                    tarGetid: this.materielNoObj.id,
                    createBy: this.createBy,
                    standingBookId: this.materielNoObj.standingBookId,
                    applyUseId: this.materielNoObj.applyUseId,
                    materielNo: this.materielNoObj.materielNo,
                    purchaseOrderNo: this.searchParams.purchaseOrderNo,
                    assets: obj.assets,//资产残值
                    purchasePrice: obj.purchasePrice,
                    assetsOriginal: obj.assetsOriginal,//资产原值
                    revertNum: obj.scrapCount,//报废数量
                    scrapCount: obj.scrapCount,//报废数量
                    manageType: obj.manageType,//管理类型
                    useTime: obj.useTime,//使用时间
                    useDept: obj.useDept,//使用部门
                    deptCostCenter: obj.deptCostCenter,//部门成本中心
                    scrapReason: obj.scrapReason,//报废原因
                    remark: obj.scrapReason,//报废原因
                    warehouseName: obj.warehouseName,
                    goodsName: obj.goodsName,
                    specification: obj.specification,
                    companyName: obj.companyName,
                    companyId: obj.companyId,
                    scraped: this.searchParams.scraped,
                    // warehouseId:obj.backupConfigId,
                    // shelfConfigId:obj.shelfConfigId,
                    // locationId:obj.locationConfigId,//库位id
                    warehouseId: this.materielNoObj.warehouseId,
                    locationId: this.materielNoObj.locationId,
                    shelfConfigId: this.materielNoObj.shelfConfigId,
                    quantityInStock: obj.quantityInStock
                }
            } else {
                tableObj = {
                    id: obj.id,
                    tarGetid: this.materielNoObj.id,
                    createBy: this.createBy,
                    standingBookId: this.materielNoObj.standingBookId,
                    applyUseId: this.materielNoObj.applyUseId,
                    companyId: this.searchParams.companyId,
                    companyName: this.searchParams.companyName,
                    materielNo: this.materielNoObj.materielNo,
                    purchaseOrderNo: this.searchParams.purchaseOrderNo,
                    goodsName: this.materielNoObj.goodsName,
                    specification: this.materielNoObj.specification,
                    revertNum: this.materielNoObj.applyNum,
                    scrapCount: this.materielNoObj.applyNum,
                    scraped: this.searchParams.scraped,
                    warehouseId: this.materielNoObj.warehouseId,
                    locationId: this.materielNoObj.locationId,
                    shelfConfigId: this.materielNoObj.shelfConfigId,
                }
            }
            this.tablelist.push(tableObj)
            this.tablelist.forEach(async val => {
                await this.getBackupsByCompany(this.searchParams.companyId, tableObj)
            })
            this.searchParams = {}
            this.materielNoList = []
        },
        //公司查仓库
        getBackupsByCompany(companyId, row) {
            if (!companyId) {
                return;
            }
            let params = {
                companyId
            }
            return getBackupsByCompany(params).then(async res => {
                if (res.code === 200) {
                    if (row) {
                        res.data.forEach(val => {
                            if (val.id === row.warehouseId) {
                                this.$set(row, 'warehouseName', val.backupName)
                            }
                        })
                        this.$set(row, 'warehouserowList', res.data)
                        await this.warehouseChange(1, row)
                    }
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        //仓库查货架
        warehouseChange(delIds, row) {
            if (!delIds) {
                return;
            }
            let warehouseName;
            const obj = row.warehouserowList.find(val => val.id === row.warehouseId)
            if (obj) {
                warehouseName = obj.backupName
            }
            let params = {
                delIds: [delIds]
            }
            if (Number(this.searchParams.scraped) !== 1) {
                params.standingBookId = row.standingBookId
            }
            if (row) {
                params.delIds = [row.warehouseId]
            }
            return getShelfByBackupId(params).then(async res => {
                if (res.code === 200) {
                    if (row) {
                        this.tablelist.forEach(val => {
                            if (val.id === row.id) {
                                this.$set(val, 'warehouseId', row.warehouseId)
                                this.$set(val, 'shelvesrowList', res.data)
                                this.$set(val, 'warehouseName', warehouseName)
                            }
                        })
                        await this.shelvesChange(1, row)
                    }
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        shelvesChange(delIds, row) {
            let fun;
            if (!delIds) {
                return;
            }
            let shelf;
            if (row.shelvesrowList && row.shelvesrowList.length) {
                const obj = row.shelvesrowList.find(val => val.id === row.shelfConfigId)
                if (obj) {
                    shelf = obj.shelf
                }
            }
            // const shelf = row.shelvesrowList.find(val=>val.id === row.shelfConfigId).shelf
            let params = {
                delIds: [delIds]
            }
            if (Number(this.searchParams.scraped) !== 1) {
                params.standingBookId = row.standingBookId
            }
            if (row) {
                params.delIds = [row.shelfConfigId]
            }
            if (this.tarGetscraped == 1) {
                params.shelfId = params.delIds.join(',')
                params.delIds = undefined
                params.standingBookId = undefined
                params.scrapStatus = 1
                fun = baogetLocationByShelfId
            } else {
                fun = getLocationByShelfId
            }
            return fun(params).then(res => {
                if (res.code === 200) {
                    if (row) {
                        this.tablelist.forEach(val => {
                            if (val.id === row.id) {
                                this.$set(val, 'shelfConfigId', row.shelfConfigId)
                                this.$set(val, 'locationrowList', res.data)
                                this.$set(val, 'shelf', shelf)
                            }
                        })
                        this.locationChange(row)
                    }
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        locationChange(row) {
            const location = row.locationrowList.find(val => val.id === row.locationId).location
            this.tablelist.forEach(val => {
                if (val.id === row.id) {
                    this.$set(val, 'locationId', row.locationId)
                    val.revertNum = Number(row.revertNum)
                    this.$set(val, 'location', location)
                }
            })
        },
        handlePurchaseOrderNo(val) {
            if (val) {
                this.materielNoObj = this.backupNoList.find(item => item.label === val)
                this.searchParams.companyId = this.materielNoObj.companyId;
                this.changeCompany(this.materielNoObj.companyId)
                this.searchParams.deviceNo = this.materielNoObj.deviceNo;
                this.searchParams.materielNo = this.materielNoObj.id;
                this.remoteMethod(this.materielNoObj.materielNo)
            } else {
                this.searchParams.deviceNo = '';
            }
        },
        handleMaterielNo(val) {
            if (val) {
                this.materielNoObj = this.materielNoList.find(item => item.id === val)
                this.backupNoList = [this.materielNoObj].map(val => ({
                    label: val.purchaseOrderNo,
                    value: val.purchaseOrderNo,
                   ...this.materielNoObj
                }))
              this.searchParams.companyId = this.materielNoObj.companyId;
              this.changeCompany(this.materielNoObj.companyId)
              this.searchParams.deviceNo = this.materielNoObj.deviceNo;
            } else {
              this.searchParams.deviceNo = '';
            }
        },
      remoteMethodOne(text) {
        const params = {
          text:this.searchParams.materielNo,
          purchaseOrderNo:text
        }
        if (this.tablelist && this.tablelist.length) {
          params.afterIds = this.tablelist.map(val => val.tarGetid).join(',')
        }
        this.axios({
          method: 'get',
          url: '/dms/revert/beforeSearch',
          params
        }).then(res => {
          if (res.code === 200) {
            this.backupNoList = res.data.map(val=>({
              label: val.purchaseOrderNo,
              value: val.purchaseOrderNo,
              ...val
            }))
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        })
      },
        remoteMethod(text) {
            // if (this.materielNoList && this.materielNoList.length){
            //   return
            // }
            const params = {
                text,
              purchaseOrderNo:this.searchParams.purchaseOrderNo
            }
            if (this.tablelist && this.tablelist.length) {
                params.afterIds = this.tablelist.map(val => val.tarGetid).join(',')
            }
            this.axios({
                method: 'get',
                url: '/dms/revert/beforeSearch',
                params
            }).then(res => {
                if (res.code === 200) {
                  this.materielNoList = res.data
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        delRow(row) {
            this.tablelist = this.tablelist.filter(val => val.id !== row.id)
        },
        searchList() {
            let params = {
                warehouseId: this.$route.query.warehouseId
            }
            this.axios({
                method: 'get',
                url: '/dms/revert/query',
                params
            }).then(res => {
                if (res.code === 200) {
                    // if (res.data[0].hasOwnProperty('useTime')){
                    //   this.columnsInfo = this.scrapTableColumns
                    // }else {
                    //   this.columnsInfo = this.tableColumns
                    // }
                    this.tablelist = res.data
                    this.tablelist.forEach(async val => {
                        if (val.revertNum) {
                            val.scrapCount = val.revertNum
                        }
                        if (val.companyId) {
                            await this.getBackupsByCompany(val.companyId, val)
                        }
                    })
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        close() {
            this.$router.go(-1)
        },
        //公司列表
        getCompanyList() {
            this.axios({
                method: 'get',
                url: '/basic/company/getCompanyListByUser',
                params: {}
            }).then(res => {
                if (res.code === 200) {
                    let arr = res.data.map(item => {
                        return {
                            ...item,
                            id: item.id
                        }
                    })
                    this.tagList = [...this.tagList, ...arr]
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        }
    }
}
</script>

<style scoped lang="scss">
/deep/ .ivu-input{
  border: 1px solid #dcdee2 !important;
}
.tableContent {
    // margin-top: 6px;
    .operationBtn {
        //color: #3271f0;
        //cursor: pointer;
        //margin: 0 10px;
    }
}

.picking {
    height: 95%;
    position: relative;
    //height: 82vh;
    overflow-y: scroll;

    .btnList {
        position: fixed;
        bottom: 20px;
        left: 50%;

        .ivu-btn {
            margin: 0 5px;
        }
    }
}

.ivu-card-body {
    padding: 0;
}

.basic-info {
    //padding: 5px 16px;
    //border-bottom: 1px solid #e8eaec;

    .basic-info-body {
        color: #333;
        font-size: 13px;
        font-family: 'Arial Normal', 'Arial', sans-serif;
        font-weight: 400;
        //margin: 10px;

        .basic-info-body-label {
            width: 100%;
            height: 48px;
            line-height: 48px;
            background: #f5f6f7;
            text-align: center;
            padding-left: 10px;
        }

        .basic-info-body-item {
            height: 48px;
            line-height: 48px;
            text-align: left;
            padding: 0 10px;
            border-left: 1px solid #eee;
            border-right: 1px solid #eee;
        }
    }

    .basic-info-title_bot {
        margin-top: 16px;
    }

    .basic-info-title {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .add {
            cursor: pointer;
            display: flex;
            align-items: center;
            padding: 0 10px;

            .addIcon {
                font-size: 28px;
            }

            .addTitle {
                font-size: 16px;
            }
        }

        h2 {
            display: inline-block;
            font-size: 16px;
            padding-left: 10px;
            position: relative;

            &::before {
                content: "";
                position: absolute;
                left: 0;
                top: 0;
                width: 7px;
                height: 24px;
                background: #187bdb;
            }
        }
    }

    .search-form {
        padding: 0;

        .ivu-form-item {
            margin: 0;
        }
    }
}
</style>
<style>
.nopad .ivu-card-body{
  padding: 0 !important;
}
</style>
